package com.hefan.user.dao;

import com.hefan.common.orm.dao.CommonDaoImpl;
import com.hefan.user.bean.WebUser;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by lxw on 2016/9/26.
 */
@Repository
public class WebUserDao extends CommonDaoImpl {
    private static String TABLE_NAME = "web_user";

    private Map<String, Object> createMapper(WebUser webUser) {
        return null;
    }

    /**
     * 新增注册普通用户
     *
     * @param webUser
     * @return
     */
    public WebUser saveRegistWebUser(WebUser webUser) {
       /* Map<String,Object> parameters =  new HashMap<String,Object>();
        parameters.put("user_id",webUser.getUserId());
        parameters.put("nick_name",webUser.getNickName());
        parameters.put("mobile",webUser.getMobile());
        parameters.put("openid_wb",webUser.getOpenidWb());
        parameters.put("openid_wx",webUser.getOpenidWx());
        parameters.put("openid_qq",webUser.getOpenidQq());
        parameters.put("user_type",webUser.getUserType());
        parameters.put("im_token",webUser.getImToken());
        parameters.put("head_img",webUser.getHeadImg());
        String[] columns = parameters.keySet().toArray(new String[]{});
        SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(getJdbcTemplate().getDataSource())
                .usingColumns(columns)
                .withTableName(TABLE_NAME)
                .usingGeneratedKeyColumns("id");
        Number id = simpleJdbcInsert.executeAndReturnKey(parameters);
        return get(id.longValue(),TABLE_NAME,webUser.getClass());*/

        List params = new ArrayList();
        params.add(webUser.getUserId());
        params.add(webUser.getNickName());
        params.add(webUser.getMobile());
        params.add(webUser.getOpenidWb());
        params.add(webUser.getOpenidWx());
        params.add(webUser.getOpenidQq());
        params.add(webUser.getUserType());
        params.add(webUser.getImToken());
        params.add(webUser.getHeadImg());
        params.add(webUser.getUnionidWx());
        StringBuilder sql = new StringBuilder("insert ignore into web_user(user_id,nick_name,mobile,openid_wb,openid_wx,openid_qq,user_type,im_token,head_img,unionid_wx)");
        sql.append("values ( ?,?,?,?,?,?,?,?,?,?)");
        int row = this.update(sql.toString(), params);
        if (row > 0) {
            return this.getWebUserBaseInfo(webUser.getUserId());
        } else {
            return null;
        }
    }

    /**
     * 根据用户userId更新用户基本信息
     *
     * @param webUser
     * @return
     */
    public int updateWebUserBaseInfo(WebUser webUser) {
        List<Object> paramsList = new ArrayList<Object>();
        StringBuilder sql = new StringBuilder("update web_user set ");
        StringBuilder updateSql = new StringBuilder();
        if (StringUtils.isNotBlank(webUser.getHeadImg())) {
            updateSql.append(",head_img=? ");
            paramsList.add(webUser.getHeadImg());
        }
        if (StringUtils.isNotBlank(webUser.getNickName())) {
            updateSql.append(",nick_name=? ");
            paramsList.add(webUser.getNickName());
        }
        if (StringUtils.isNotBlank(webUser.getStar())) {
            updateSql.append(",star=? ");
            paramsList.add(webUser.getStar());
        }
        if (webUser.getPersonSign() != null) {
            updateSql.append(",person_sign=? ");
            paramsList.add(webUser.getPersonSign());
        }
        if (StringUtils.isNotBlank(webUser.getFeeling())) {
            updateSql.append(",feeling=? ");
            paramsList.add(webUser.getFeeling());
        }
        if (webUser.getJob() != null) {
            updateSql.append(",job=? ");
            paramsList.add(webUser.getJob());
        }
        if (StringUtils.isNotBlank(webUser.getProvince())) {
            updateSql.append(",province=? ");
            paramsList.add(webUser.getProvince());
        }
        if (StringUtils.isNotBlank(webUser.getCity())) {
            updateSql.append(",city=? ");
            paramsList.add(webUser.getCity());
        }
        if (StringUtils.isNotBlank(webUser.getBackGround())) {
            updateSql.append(",back_ground=? ");
            paramsList.add(webUser.getBackGround());
        }
        if (webUser.getBirthday() != null) {
            updateSql.append(",birthday=? ");
            paramsList.add(webUser.getBirthday());
        }
        if (webUser.getSex() != null) {
            updateSql.append(",sex=? ");
            paramsList.add(webUser.getSex());
        }
        if (webUser.getAge() != null) {
            updateSql.append(",age=? ");
            paramsList.add(webUser.getAge());
        }

        if (StringUtils.isNotBlank(updateSql.toString())) {
            String sqlTemp = updateSql.toString();
            sql.append(sqlTemp.substring(1)).append("where user_id=?");
            paramsList.add(webUser.getUserId());
        } else {
            return 0;
        }
        return this.update(sql.toString(), paramsList);
    }

    public int getWebUserCountByQueryVal(String queryVal, int paramType, int isDel) {
        StringBuilder sqlBuilder = new StringBuilder("select count(1) from  web_user where ");
        //判断查询条件类型
        switch (paramType) {
            case 0:
                sqlBuilder.append(" user_id=? ");
                break;
            case 1:  //微博openId查询
                sqlBuilder.append(" openid_wb=? ");
                break;
            case 2: //微信openId查询
                sqlBuilder.append(" openid_wx=? ");
                break;
            case 3: //QQ的openId查询
                sqlBuilder.append(" openid_qq=? ");
                break;
            case 4: //手机号查询
                sqlBuilder.append(" mobile=? ");
                break;
            case 5:
                sqlBuilder.append(" unionid_wx=? ");
                break;
            default:
                return 0;
        }
        //是否有删除标识条件
        switch (isDel) {
            case 0:  //正常
                sqlBuilder.append(" and is_del=0 ");
                break;
            case 1: //已删除
                sqlBuilder.append(" and is_del=1 ");
                break;
            case 2: //全部
                break;
            default:
                break;
        }

        return this.queryCount(sqlBuilder.toString(), queryVal);
    }

    /**
     * 根据用户id和是否已删除条件查询用户信息
     * @param userId 用户id
     * @param isDel 0 只查询正常  1 只查询删除  2 全部包含
     * @return
     */
    public WebUser getWebUserInfoByIsDel(String userId,int isDel) {
        StringBuilder sqlBuilder = new StringBuilder( "select * from web_user where user_id=? ");
        //是否有删除标识条件
        switch (isDel) {
            case 0:  //正常
                sqlBuilder.append(" and is_del=0 ");
                break;
            case 1: //已删除
                sqlBuilder.append(" and is_del=1 ");
                break;
            case 2: //全部
                break;
            default:
                break;
        }
        List<Object> params = new ArrayList<Object>();
        params.add(userId);
        return this.get(sqlBuilder.toString(), params, WebUser.class);
    }

    /**
     * 获取用户基本信息
     *
     * @param userId
     * @return
     */
    public WebUser getWebUserBaseInfo(String userId) {
        String sql = "select * from web_user where user_id=? and is_del=0";
        List<Object> params = new ArrayList<Object>();
        params.add(userId);
        return this.get(sql, params, WebUser.class);
    }

    /**
     * 根据第三方账号获取用户信息
     *
     * @param type
     * @param thridOpendId
     * @return
     */
    public WebUser getWebUserInfoByUserIdList(int type, String thridOpendId) {
        List<Object> params = new ArrayList<Object>();
        params.add(thridOpendId);
        StringBuilder sqlBuilder = new StringBuilder("select * from web_user where is_del=0 and ");
        if (type == 1) { //微博openId查询
            sqlBuilder.append(" openid_wb=?");
        } else if (type == 2) { //微信openId查询
            sqlBuilder.append(" openid_wx=?");
        } else if (type == 3) {//QQ的openId查询
            sqlBuilder.append(" openid_qq=?");
        } else if (type == 4) {//手机号查询
            sqlBuilder.append(" mobile=?");
        } else if(type == 5) { //根据微信unionid查询
            sqlBuilder.append(" unionid_wx=?");
        } else {
            return null;
        }
        return this.get(sqlBuilder.toString(), params, WebUser.class);
    }


    /**
     * 根据多个用户id获取用户基本信息列表
     *
     * @param userIdList
     * @return
     */
    public List getWebUserInfoByUserIdList(List userIdList) {
        StringBuilder sqlBuilder = new StringBuilder("select * from web_user where is_del=0 and user_id in (");
        for (int i = 0; i < userIdList.size(); i++) {
            if (i == 0) {
                sqlBuilder.append("?");
            } else {
                sqlBuilder.append(",?");
            }
        }
        sqlBuilder.append(") limit 100");
        return this.query(sqlBuilder.toString(), userIdList.toArray(), WebUser.class);
    }

    /**
     * 更新用户等级
     *
     * @param userId
     * @param userLevel
     * @param incrExp
     * @return
     */
    public int updateWebUserLevelInfo(String userId, int userLevel, long incrExp) {
        String sql = "update web_user set user_level=?,exp=exp+? where user_id=?";
        return this.update(sql, new Object[]{userLevel, incrExp, userId});
    }

    /**
     * 更新DB中用户累计盒饭数和等级
     *
     * @param incrMode  1 累计更新  2 全量更新
     * @param userId
     * @param hefanVal
     * @param userLevel
     * @return
     */
    public int updateUserHefanTotalDb(int incrMode, String userId, long hefanVal, int userLevel) {
        String incrSql = "hefan_total+";
        if (incrMode == 2) incrSql = "";
        String sql = "update web_user set hefan_total=" + incrSql + "?,user_level=? where user_id=?";
        return this.update(sql, new Object[]{hefanVal, userLevel, userId});
    }

    /**
     * 更新DB中用户饭票数据
     *
     * @param incrMode 1 累计更新  2 全量更新
     * @param userId
     * @param balance
     * @return
     */
    public int updateUserBalanceDb(int incrMode, String userId, long balance) {
        String incrSql = "balance+";
        if (incrMode == 2) incrSql = "";
        String sql = "update web_user set balance=" + incrSql + "? where user_id=?";
        Object[] params = new Object[]{balance, userId};
        return this.update(sql, params);
    }

    /**
     * 更新DB中用户的贡献值
     *
     * @param incrMode 1 累计更新  2 全量更新
     * @param userId
     * @param payCount
     * @return
     */
    public int updateUserPayCountDb(int incrMode, String userId, long payCount) {
        String incrSql = "pay_count+";
        if (incrMode == 2) incrSql = "";
        String sql = "update web_user set pay_count=" + incrSql + "? where user_id=?";
        Object[] params = new Object[]{payCount, userId};
        return this.update(sql, params);
    }

    /**
     * 更新DB中普通用户的经验和等级
     *
     * @param incrMode
     * @param userId
     * @param incrExp
     * @param userLevel
     * @return
     */
    public int updateUserExpDb(int incrMode, String userId, long incrExp, int userLevel) {
        String incrSql = "exp+";
        if (incrMode == 2) incrSql = "";
        String sql = "update web_user set user_level=?,exp=" + incrSql + "? where user_id=?";
        return this.update(sql, new Object[]{userLevel, incrExp, userId});
    }

    public List<Map<String, Object>> getEntityList(String sql, String placeholder, Set<String> selector) {
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue(placeholder, selector);
        return getNamedParameterJdbcTemplate().queryForList(sql, parameters);
    }

    public List<WebUser> getEntityList2(String sql, String placeholder, Set<String> selector) {
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        parameters.addValue(placeholder, selector);
        return getNamedParameterJdbcTemplate().query(sql, parameters,new BeanPropertyRowMapper(WebUser.class));
    }

    public WebUser getDynaUser(String userId) {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT");
        sql.append(" wu.user_id,wu.age,wu.star,wu.auth_info,wu.back_ground,wu.pay_count payCount, wu.auth_id, ");
        sql.append("  IFNULL(wi.status,'0') status,");
        sql.append(
                " wu.person_sign,wu.user_type ,wu.head_img,wu.sex,wu.nick_name,wu.birthday,wu.user_level,wu.hefan_total, ");
        sql.append(" wi.profiles ,IFNULL(wi.info_file,'') infoFile");
        sql.append(" FROM web_user wu");
        sql.append(" LEFT JOIN web_user_identity wi");
        sql.append(" on wu.user_id=wi.user_id");
        sql.append(" WHERE wu.user_id =?");
        List<WebUser> message = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper(WebUser.class),
                userId);
        return CollectionUtils.isEmpty(message) ? null : message.get(0);
    }

    public WebUser getDynaNormalUser(String userId) {
        StringBuilder sql = new StringBuilder();
        sql.append(" SELECT");
        sql.append(" wu.user_id,wu.age,wu.star,wu.auth_info,wu.back_ground,wu.pay_count payCount, wu.auth_id, ");
//        sql.append("  IFNULL(wi.status,'0') status,");
        sql.append(
                " wu.person_sign,wu.user_type ,wu.head_img,wu.sex,wu.nick_name,wu.birthday,wu.user_level,wu.hefan_total ");
//        sql.append(" wi.profiles ,wi.info_file infoFile");
        sql.append(" FROM web_user wu");
//        sql.append(" LEFT JOIN web_user_identity wi");
//        sql.append(" on wu.user_id=wi.user_id");
        sql.append(" WHERE wu.user_id =?");
        List<WebUser> message = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper(WebUser.class),
                userId);
        return CollectionUtils.isEmpty(message) ? null : message.get(0);
    }

    /**
     * 更新用户微信openId信息
     * @param userId
     * @param wxOpenId
     * @return
     */
    public int modifyNewWxOpenId(String userId, String wxOpenId) {
        String sql = "update web_user set openid_wx=? where user_id=?";
        List<Object> paramsList = new ArrayList<Object>();
        paramsList.add(wxOpenId);
        paramsList.add(userId);
        return this.update(sql,paramsList);
    }

    /**
     * 获取某一时间点之后的无效用户信息
     * @param updateTimeStr
     * @return
     * @throws Exception
     */
    public List<WebUser> findInvalidUserInfoByUpdateTime(String updateTimeStr) throws Exception {
        String sql = "SELECT * FROM web_user WHERE (is_del=0 OR state+superior_state>0) AND update_time >=?";
        return this.getJdbcTemplate().queryForList(sql,new Object[] {updateTimeStr}, WebUser.class);
    }

    /**
     * 更新用户的unionidWx
     * @param userId
     * @param unionidWx
     * @return
     * @throws Exception
     */
    public int updateWebUserUnionidWx(String userId,String unionidWx) throws Exception {
        String sql = "update web_user set unionid_wx=? where user_id=?";
        List<Object> paramsList = new ArrayList<Object>();
        paramsList.add(unionidWx);
        paramsList.add(userId);
        return this.update(sql,paramsList);
    }
}
